/**
 * Project Name:HomeActivity
 * Date:2016-6-13下午2:54:48
 * Copyright (c) 2016, askzhao All Rights Reserved.
 *
 */
package com.kkd.kkdapp.http.manager;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import android.text.TextUtils;

import com.kkd.kkdapp.utils.FileUtils;
import com.kkd.kkdapp.utils.MD5;

/**
 * ClassName: DownFileManager <br/>
 * date: 2016-6-13 下午2:54:48 <br/>
 * 
 * @author askzhao
 * @version
 */
public class DownFileManager {

	private static DownFileManager instance;
	private ArrayList<String> mDownQueen = new ArrayList<String>();

	public static DownFileManager getInstance() {
		if (instance == null) {
			instance = new DownFileManager();
		}
		return instance;
	}

	private class downFileRunnable implements Runnable {

		private String savePath;
		private String saveFileName;
		private DownLoadCallback mCallback;
		private int progress;
		private boolean interceptFlag = false;
		private String fileUrl;

		public downFileRunnable(String savePath, String fileUrl,
				DownLoadCallback callback) {
			mCallback = callback;
			this.savePath = savePath;
			this.fileUrl = fileUrl;
			saveFileName = savePath + MD5.Md5(fileUrl) + ".kkd";
			progress = 0;
		}

		public void run() {

			try {
				URL url = new URL(fileUrl);

				HttpURLConnection conn = (HttpURLConnection) url
						.openConnection();
				conn.connect();
				int length = conn.getContentLength();
				InputStream is = conn.getInputStream();

				File file = new File(savePath);
				if (!file.exists()) {
					file.mkdir();
				}

				File nfile = new File(saveFileName);
				FileOutputStream fos = new FileOutputStream(nfile);

				int count = 0;
				byte buf[] = new byte[1024];

				do {
					int numread = is.read(buf);
					count += numread;
					progress = (int) (((float) count / length) * 100);
					// 更新进度
					mCallback.onProgress(progress);
					if (numread <= 0) {
						// 下载完成通知安装
						mCallback.onFinish();
						break;
					}
					fos.write(buf, 0, numread);
				} while (!interceptFlag);// 点击取消就停止下载.

				fos.close();
				is.close();

			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}

	/**
	 * 下载apk
	 * 
	 * @param url
	 */

	public void downloadFile(final String savePath, final String fileUrl,final String fileName,
			final String fileType, final DownLoadCallback callback) {
		
		File file = new File(savePath);
		if (!file.exists()) {
			file.mkdirs();
		}
		for (String u : mDownQueen) { // 遍历一下下载队列，已存在的下载任务直接忽略
			if (u.equals(fileUrl)) {
				callback.onDownLoading();
				return;
			}
		}

		String filePath = savePath + MD5.Md5(fileUrl) + fileType;
		if (FileUtils.isFileUrlExit(filePath)) {// 下载过的文件不再下载
			callback.onFinish();
			return;
		}
		// 新任务添加到队列
		mDownQueen.add(fileUrl);
		Thread downLoadThread = new Thread(new downFileRunnable(
				FileUtils.getKKDRootPath() + "temp/", fileUrl,
				new DownLoadCallback() {

					@Override
					public void onProgress(int progress) {
						callback.onProgress(progress);
					}

					@Override
					public void onFinish() {
						if(TextUtils.isEmpty(fileName)){
							FileUtils.copyFile(FileUtils.getKKDRootPath() + "temp/"
									+ MD5.Md5(fileUrl) + ".kkd",
									savePath + MD5.Md5(fileUrl) +  "."+fileType);
						}else{
							FileUtils.copyFile(FileUtils.getKKDRootPath() + "temp/"
									+ MD5.Md5(fileUrl) + ".kkd",
									savePath + fileName);
						}
						mDownQueen.remove(fileUrl);
						callback.onFinish();
					}

					@Override
					public void onDownLoading() {
						callback.onDownLoading();
					}

					@Override
					public void onCancle() {
						callback.onCancle();
					}
				}));
		downLoadThread.start();

	}

	public interface DownLoadCallback {
		public void onProgress(int progress);

		public void onDownLoading();

		public void onCancle();

		public void onFinish();
	}

}
